所谓坑
其实也算不上坑,只能说没理解好path.join的用法,
path.join()
有两个要注意的地方
- 台特定的分隔符[Unix系统是/,Windows系统是\ ]
- ‘..’作为上一级路径 应该放在拼接的后面
- join是把各个path片段连接在一起,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| __dirname
const path = require('path');
const path1 = path.join(__dirname, '/foo'); const path2 = path.join(__dirname, './foo/bar'); const path3 = path.join('/foo', 'bar', '/baz/apple', 'aaa', '..'); const path4 = path.join('foo', 'bar', 'baz'); const path5 = path.join('foo', 'bar', '..', '..')
console.log(path1); console.log(path2); console.log(path3); console.log(path4); console.log(path5);
/Users/Admin/work/test/foo /Users/Admin/work/test/foo/bar /foo/bar/baz/apple foo/bar/baz .
|
path.resolve()
resolve操作相当于进行了一系列的cd操作,把‘/’当成根目录
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| const path = require('path');
const path1 = path.resolve('/a/b', '/c/d');
const path2 = path.resolve('/a/b', 'c/d');
const path3 = path.resolve('/a/b', '../c/d');
const path4 = path.resolve('a', 'b');
```
## 扯远一点
### process.cwd()和__dirname的区别
>1. process.cwd()返回当前工作目录。如:调用node命令执行脚本时的目录。 >2. __dirname返回源代码所在的目录。
``` javascript
console.log(`cwd: ${process.cwd()}`); console.log(`dirname: ${__dirname}`);
|
命令 | process.cwd() | __dirname |
---|
node index.js | d:\dir单元格 | d:\dir s |
node dir\index.js | d: | d:\dir |